package com.hui.wanxin.web.utils;


import com.hui.wanxin.web.entity.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;

public class JwtUtils {

    private static final long EXPIRE = 60000*60*24*3;
    /**
     * 密钥
     */
    private static final String SECRET="wanxin.com";
    /**
     * 前缀
     */
    private static final String TOKEN_PREIX="wanxin";
    /**
     *主题
     */
    private static final String SUBJECT="wanxin";

    /**
     * 根据用户生成令牌
     * @param user
     * @return
     */
    public static String geneJsonWebToken(User user){
        String token = Jwts.builder()
                .setSubject(SUBJECT)
                .claim("openid",user.getOpenid())
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE))
                .signWith(SignatureAlgorithm.HS256, SECRET).compact();
        token = TOKEN_PREIX+token;
        return token;
    }

    /**
     * 校验Token
     * @param token
     * @return
     */
    public static Claims checkToken(String token){
        try {
            Claims claims = Jwts.parser().setSigningKey(SECRET).parseClaimsJws(token.replace(TOKEN_PREIX, "")).getBody();
            return claims;
        } catch (Exception e) {
            return null;
        }
    }
}